﻿using System;
using Zo.Exceptions;
using Zo.Events;

namespace Zo.Domain.UnitOfWorks.Default
{
    public class UnitOfWorkFactory : IUnitOfWorkFactory
    {
        private readonly IEventBus _EventBus;

        [ThreadStatic]
        private static IUnitOfWork _unitOfWork = null;

        public UnitOfWorkFactory(IEventBus EventBus)
        {
            _EventBus = EventBus;
        }

        public IUnitOfWork Create()
        {
            if (_unitOfWork != null)
            {
                throw new MainApplicationException("生成事务错误");
            }

            _unitOfWork = new UnitOfWork(this, _EventBus);

            return _unitOfWork;
        }

        public IUnitOfWork Get()
        {
            return _unitOfWork;
        }

        public void Remove()
        {
            _unitOfWork = null;
        }
    }
}